package com.gzx.file.controller;

import com.gzx.file.http.RETemplate;
import com.gzx.file.service.FileService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 文件上传服务
 */
@Api(value = "/file", tags = "文件服务模块")
@RequestMapping("/file")
@RestController
public class FileController {

    @Autowired
    FileService fileService;

    @GetMapping("/{fileType}/{fileName}")
    public void getFile(HttpServletResponse res, @PathVariable Integer fileType, @PathVariable String fileName) {
        File file = null;
        file = fileService.getFile(fileType, fileName);
//        res.setHeader("content-type", "application/octet-stream");
//        res.setContentType("application/form-data");
//        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//        System.out.println("success");
    }


    /**
     * 保存文件
     * <p>
     * 用 form-data(表单数据)的方式传递过来
     * 文件件统一用file作为key,value为文件
     * <p>
     * 附带 fileType来区分存放路径 默认规则  0图片 1媒体 2数据 3音频  其他为 文件类型 优先级从左到右
     * <p>
     * 返回的文件url是由地址前缀代替真实地址
     *
     * @param multipartFiles 文件 集合
     * @param fileType       文件类型(多文件需要统一一个类型)
     * @return 文件转url的集合
     */
    @PostMapping("/upload")
    public ResponseEntity uploadFile(@RequestParam("file") List<MultipartFile> multipartFiles, @RequestParam(value = "fileType", defaultValue = "10") int fileType) {
        List<String> fileHttpUrl = null;
        try {
            fileHttpUrl = fileService.saveFile(fileType, multipartFiles);
        } catch (IOException e) {
            e.printStackTrace();
            return RETemplate.failure("文件上传失败,请稍后重试");
        }
        if (fileHttpUrl == null) {
            return RETemplate.failure("文件上传失败,请稍后重试");
        }
        return RETemplate.ok(fileHttpUrl);
    }

}
